﻿using System;
using System.Messaging;
using System.Windows.Forms;
using Message = System.Messaging.Message;
using DataAccess.DataAccess;

namespace ClientAdminServer
{
    static class Program
    {
        private static readonly string QueuePaymentClientSend = Properties.Settings.Default.QueuePaymentClientSend;
        private static readonly string QueuePaymentClientReceive = Properties.Settings.Default.QueuePaymentClientReceive;
        private static readonly string QueueComClientSend = Properties.Settings.Default.QueueComClientSend;
        private static readonly string QueueComClientReceive = Properties.Settings.Default.QueueComClientReceive;
        
        /// <summary>
        /// Punto de entrada principal para la aplicación.
        /// </summary>
        [STAThread]
        static void Main()
        {
            MessageQueue msMqReceived = new MessageQueue(QueueComClientSend);
            try
            {
                msMqReceived.Formatter = new XmlMessageFormatter(new[] { typeof(string) });
                msMqReceived.ReceiveCompleted += MyReceiveCompleted;
                msMqReceived.Purge();
                msMqReceived.BeginReceive();
            }
            catch (MessageQueueException ee)
            {
                Console.Write(ee.ToString());
                msMqReceived.Close();
            }
            catch (Exception eee)
            {
                Console.Write(eee.ToString());
                msMqReceived.Close();
            }
            MessageQueue msMqReceivedPayment = new MessageQueue(QueuePaymentClientSend);
            try
            {
                msMqReceivedPayment.Formatter = new XmlMessageFormatter(new[] { typeof(string) });
                msMqReceivedPayment.ReceiveCompleted += MyReceiveCompletedPayment;
                msMqReceivedPayment.BeginReceive();
            }
            catch (MessageQueueException ee)
            {
                Console.Write(ee.ToString());
                msMqReceivedPayment.Close();
            }
            catch (Exception eee)
            {
                Console.Write(eee.ToString());
                msMqReceivedPayment.Close();
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new UserForm());
        }

        private static void MyReceiveCompletedPayment(object source, ReceiveCompletedEventArgs asyncResult)
        {
            decimal resultado;
            MessageQueue msMqReceived = (MessageQueue)source;
            try
            {
                msMqReceived.Formatter = new XmlMessageFormatter(new[] { typeof(string) });
                Message message = msMqReceived.EndReceive(asyncResult.AsyncResult);
                //================== realizar operacion sobre el mensaje =============================
                if (message != null && message.Body != null)
                {
                    var result = message.Body.ToString().Split('|');
                    if (result.Length == 4)
                    {
                        int idOperacion = Convert.ToInt32(result[0]);
                        int userId = Convert.ToInt32(result[1]);
                        decimal kilometros = Convert.ToDecimal(result[2]);
                        string estado = result[3];
                        bool isPrepaid;
                        DataAccessClass dataAccess = new DataAccessClass();

                        isPrepaid = !dataAccess.ClientePospago(userId);
                        resultado = dataAccess.ModificarViaje(userId,kilometros,estado);
                        //send response
                        MessageQueue msMq;
                        msMq = new MessageQueue(QueuePaymentClientReceive);
                        try
                        {
                            var operationMessage = string.Format("{0}|{1}|{2}|{3}", idOperacion, userId, resultado.ToString("0,0.000"),isPrepaid);// idOperacion + "|" + userId + "|" + resultado;
                            msMq.Send(operationMessage);
                        }
                        catch (MessageQueueException ee)
                        {
                            Console.Write(ee.ToString());
                        }
                        catch (Exception eee)
                        {
                            Console.Write(eee.ToString());
                        }
                        finally
                        {
                            msMq.Close();
                        }
                    }
                }
                //====================================================================================
            }
            catch (MessageQueueException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                msMqReceived.BeginReceive();
            }
        }

        private static void MyReceiveCompleted(object source, ReceiveCompletedEventArgs asyncResult)
        {
            var resultado = false;
            MessageQueue msMqReceived = (MessageQueue)source;
            
            try
            {
                msMqReceived.Formatter = new XmlMessageFormatter(new[] { typeof(string) });
                Message message = msMqReceived.EndReceive(asyncResult.AsyncResult);
                //================== realizar operacion sobre el mensaje =============================
                if (message != null && message.Body != null)
                {
                    var result = message.Body.ToString().Split('|');
                    if (result.Length == 1)
                    {
                        int userId = Convert.ToInt32(result[0]);
                        DataAccessClass dataAccess = new DataAccessClass();
                        resultado = dataAccess.IniciarViaje(userId);
                        
                        MessageQueue msMq;
                        msMq = new MessageQueue(QueueComClientReceive);
                        try
                        {
                            var operationMessage = userId + "|" + resultado ;
                            msMq.Send(operationMessage);
                        }
                        catch (MessageQueueException ee)
                        {
                            Console.Write(ee.ToString());
                        }
                        catch (Exception eee)
                        {
                            Console.Write(eee.ToString());
                        }
                        finally
                        {
                            msMq.Close();
                        }
                    }
                }
                //====================================================================================
            }
            catch (MessageQueueException ex)
            {
                Console.WriteLine( ex.Message);
            }
            finally
            {
                msMqReceived.BeginReceive();
            } 
        }
    }
}
